/*
 *  manager.h
 *  xbox360wireless_receiver
 *
 *  Created by Delio Brignoli on 12/12/08.
 *  Copyright 2008 Delio Brignoli. All rights reserved.
 *
 */

#include <IOKit/IOService.h>

#define WGRManager it_drlinux_driver_XBox360WirelessGamingReceiverManager
#define stringify_(arg) #arg
#define stringify(arg) stringify_(arg)
#define READ_TIMEOUT 0
#define WRITE_TIMEOUT 0

class WGRManager : public IOService {
		OSDeclareDefaultStructors(WGRManager)

	private:
		typedef enum {
			HEADSET_DISCONNECTED = 0,
			HEADSET_CONNECTED,
			HEADSET_PAIRED
		} headsetStateEnum;
		
		typedef enum {
			CONTROLLER_DISCONNECTED = 0,
			CONTROLLER_CONNECTED,
			CONTROLLER_PAIRED
		} controllerStateEnum;
		
		typedef enum {
			INVALID = -1,
			CONTINUOUS_REPORT_UPDATE = 0,
			REPORT_UPDATE,
			CONNECTION_UPDATE
		} reportTypeEnum;
		
		OSString *serviceName;

		int mngrIndex, outstandingIOCount;
		IOUSBInterface *usbInterface;
		
		IOService *headsetDriver;
		headsetStateEnum headsetState;
		
		IOService *controllerDriver;
		controllerStateEnum controllerState;
	
		IOUSBPipe *inPipe, *outPipe;

		IOUSBCompletionWithTimeStamp readCompletion;
		IOUSBCompletion writeCompletion;
	
		AbsoluteTime lastConnectionUpdateTimestamp;

		void cleanUp(IOService *provider);
		void handleHeadsetConnection(void);
		void handleHeadsetDisconnection(void);
		void handleControllerConnection(void);
		void handleControllerDisconnection(void);
		void disableContinuousReports(void);

		bool pairHeadset(void);
		void requestConnectionUpdateReport(void);
		void notificationBeep(void);
		void successBeep(void);
		void failureBeep(void);

		void triggerDriverMatching(void);
		void terminateHeadsetDriver(void);
	
		bool asyncWrite(UInt8 *buf, int bufLength);
		bool requestAsyncRead(void);
		void handleInputReport(UInt8 *reportBuffer, int bufferLenght);
		void readComplete(void *parameter, IOReturn status, UInt32 bufferSizeRemaining, AbsoluteTime timeStamp);
		void writeComplete(void *parameter, IOReturn status, UInt32 bufferSizeRemaining);
		static void _readComplete(void *target, void *parameter, IOReturn status, UInt32 bufferSizeRemaining, AbsoluteTime timeStamp);
		static void _writeComplete(void *target, void *parameter, IOReturn status, UInt32 bufferSizeRemaining);

	public:
		virtual bool start(IOService *provider);
		virtual void stop(IOService *provider);
		virtual bool willTerminate(IOService * provider, IOOptionBits options);
		virtual bool didTerminate( IOService * provider, IOOptionBits options, bool * defer );
		virtual IOReturn message(UInt32 type,IOService *provider,void *argument);
		void registerHeadsetDriver(IOService *driver);
		void registerControllerDriver(IOService *driver);
		bool isHeadsetReady();
		bool isControllerReady();

};
